<template>
  <!-- v-pagePermissions="pagePermissions"  -->
  <div class="white-bg commonBoxmp">
    <div class="aic h100">
      <deptTree @updateDept="handleNodeClick"></deptTree>
      <TableV2
        :apiFunction="listUser"
        class="flex1"
        ref="tableV2Ref"
        :columns="state.columnData"
      >
        <template #operation>
          <el-table-column
            label="操作"
            fixed="right"
            width="160px"
            align="left"
          >
            <template #default="scope">
              <el-button type="text" @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button type="text" @click="handleDelete(scope.row)"
                >删除</el-button
              >
              <el-dropdown @command="handleMoreTool($event, scope.row)">
                <el-button class="ml10" type="text">
                  更多
                  <el-icon class="el-icon--right"> <arrow-down /> </el-icon
                ></el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="updatePwd"
                      >更换密码</el-dropdown-item
                    >
                    <el-dropdown-item command="updaterole"
                      >分配角色</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </template>
      </TableV2>
    </div>
    <el-dialog
      v-model="state.userVisible"
      :title="state.title"
      width="50%"
      destroy-on-close
      center
    >
      <el-form
        ref="ruleFormRef"
        :model="state.form"
        :rules="state.rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="state.form.nickName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-cascader
                class="w100"
                :options="state.deptOptions"
                v-model="state.form.deptId"
                :props="{
                  checkStrictly: true,
                }"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="state.form.phonenumber" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="state.form.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              v-if="state.form.userId == undefined"
              label="用户名称"
              prop="userName"
            >
              <el-input v-model="state.form.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="state.form.userId == undefined"
              label="用户密码"
              prop="password"
            >
              <el-input
                v-model="state.form.password"
                maxlength="20"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <selectDict
                class="w100"
                dictCode="sys_user_sex"
                v-model="state.form.sex"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <selectDict
                class="w100"
                dictCode="sys_normal_disable"
                v-model="state.form.status"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select
                class="w100"
                v-model="state.form.postIds"
                multiple
                placeholder="请选择岗位"
              >
                <el-option
                  v-for="item in state.postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select
                class="w100"
                v-model="state.form.roleIds"
                multiple
                placeholder="请选择角色"
              >
                <el-option
                  v-for="item in state.roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="state.form.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.userVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import {
  ref,
  reactive,
  getCurrentInstance,
  onMounted,
  toRaw,
  unref,
} from "vue";
import { useRouter, useRoute } from "vue-router";

import * as echarts from "echarts";
import deptTree from "/@/views/system/user/components/deptTree.vue";
import Column from "/@ts/components/table/Column";
import formatTool from "/@ts/hooks/format";
import selectV2 from "/@/components/selectV2/index.vue";
import selectDict from "/@/components/selectDict/index.vue";
import DictTag from "/@/components/DictTag/index.vue";

import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect,
} from "/@ts/axios/urlApi/system/user";
import { getConfigKey } from "/@ts/axios/urlApi/system/config";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
const router = useRouter();
const route = useRoute();
const { parseTime, addDateRange, getDict } = formatTool();
let dict: any = reactive({
  sys_job_status: [],
});
onMounted(async () => {
  dict.sys_job_status = await getDict("sys_job_status");
});
const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(true);
const state: any = reactive({
  initPassword: "",
  height: 0,
  deptOptions: [],
  form: {},
  // 表单校验
  rules: {
    userName: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "用户名称长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" },
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        min: 5,
        max: 20,
        message: "用户密码长度必须介于 5 和 20 之间",
        trigger: "blur",
      },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phonenumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
  dateRange: [],
  postOptions: [],
  roleOptions: [],
  tableData: [],
  userVisible: false,
  columnData: [
    {
      label: "用户名称",
      prop: "userName",
      visible: true,
                renderHeader: ({column}:any) => {
            return (      <filterBox
              title={column.label}
              valueKey={column.property}
              flterType="input"
              onChange={tableV2Ref.value.handleFilterBox}
              data={tableV2Ref.value.formFilter}
            ></filterBox>)
          },
    },
    {
      label: "用户昵称",
      prop: "nickName",
      visible: true,
             renderHeader: ({column}:any) => {
            return (      <filterBox
              title={column.label}
              valueKey={column.property}
              flterType="input"
              onChange={tableV2Ref.value.handleFilterBox}
              data={tableV2Ref.value.formFilter}
            ></filterBox>)
          },
    },
    {
      label: "部门",
      prop: "dept.deptName",
      visible: true,
    },

    {
      label: "手机号",
      prop: "phonenumber",
      visible: true,
    },
    //  <el-switch
    //                   active-value="0"
    //                   inactive-value="1"
    //                   onChange={()=>handleStatusChange(row)}
    //                   modelValue={row.status}
    //                 >
    //                 </el-switch>
    {
      label: "状态",
      prop: "status",
      visible: true,
      render: ({ row }: any) => {
        return (
          <DictTag
            values={row.status}
            dataType="primary"
            options={dict.sys_job_status}
            onClick={() => handleStatusChange(row)}
          ></DictTag>
        );
      },
    },
    {
      label: "创建时间",
      prop: "createTime",
      visible: true,
    },
  ],
  operation: {
    label: "操作",
    prop: "操作",
    width: "180",
    fixed: "right",
    visible: true,
    render: ({ row }: any) => {
      return (
        <div>
          <el-button type="primary" size="small">
            编辑
          </el-button>
          <el-button type="danger" size="small">
            删除
          </el-button>
        </div>
      );
    },
  },
  loading: false,
});
const pageInfo = reactive({
  currentPage: 1,
  total: 10,
  pageSize: 10,
  pageSizes: [10, 20, 30, 40],
  layout: "total, prev, pager, next,sizes",
});
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  deptId: undefined,
});
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  const params = unref(queryParams);
  tableV2Ref.value.getList(params);
};
//切换部门数据
const handleNodeClick = (data: any) => {
  queryParams.deptId = data.id;
  handleQuery();
};
// 用户状态修改
const handleAddUser = () => {
  getUser().then((response: any) => {
    state.form = {
      sex: "1",
    };
    state.userVisible = true;
    state.title = "添加用户";
    state.postOptions = response.posts;
    state.roleOptions = response.roles;
    state.form.password = state.initPassword;
    state.userVisible = true;
  });
};
const tableV2Ref = ref();
const handleStatusChange = (row: any) => {
  let text = row.status === "0" ? "启用" : "停用";

  ElMessageBox.confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
    .then(function () {
      const data = {
        userId: row.userId,
        status: row.status,
      };
      return changeUserStatus(data);
    })
    .then(() => {
      ElMessage.success(text + "成功");
      tableV2Ref.value.getList();
    })
    .catch(function () {
      // row.status = row.status === "0" ? "1" : "0";
    });
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate();
  if (state.form.userId != undefined) {
    updateUser(state.form).then((response: ResponseConfig) => {
      ElMessage.success("修改成功");
      state.userVisible = false;
      getList();
    });
  } else {
    addUser(state.form).then((response: ResponseConfig) => {
      ElMessage.success("新增成功");
      state.userVisible = false;
      getList();
    });
  }
};
const handleDelete = (row: any) => {
  const userIds = row.userId;
  ElMessageBox.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
    .then(function () {
      return delUser(userIds);
    })
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    })
    .catch(function () {});
};
/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  const userId = row.userId;
  getUser(userId).then((response: ResponseConfig) => {
    state.title = "修改用户";
    state.form = response.data;
    state.postOptions = response.posts;
    state.roleOptions = response.roles;
    state.form.password = "";
    state.userVisible = true;
  });
};
const updatePwd = (row: any) => {
  console.log("row :>> ", row);
  ElMessageBox.prompt("请输入新的密码", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(({ value }) => {
      resetUserPwd({
        userId: row.userId,
        password: row.value,
      }).then((res: any) => {
        ElMessage({
          type: "success",
          message: `更新成功`,
        });
        getList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Input canceled",
      });
    });
};
//更多操作
const handleMoreTool = (val: string, row: any) => {
  switch (val) {
    case "updatePwd":
      updatePwd(row);
      break;

    case "updaterole":
      handleAuthUser(row);
      break;
  }
};
const handleAuthUser = (row: any) => {
  const userId = row.userId;
  router.push("/system/user-auth/role/" + userId);
};
//查询用户列表
const getList = () => {
  state.loading = true;
  queryParams.pageNum = pageInfo.currentPage;
  queryParams.pageSize = pageInfo.pageSize;
  listUser(addDateRange(queryParams, state.dateRange)).then((response: any) => {
    state.tableData = response.rows;
    pageInfo.total = response.total;
    state.loading = false;
  });
};
/** 查询部门下拉树结构 */
const getDeptTree = () => {
  deptTreeSelect().then((response: ResponseConfig) => {
    state.deptOptions = response.data;
  });
};

onMounted(() => {
  getConfigKey("sys.user.initPassword").then((response: ResponseConfig) => {
    state.initPassword = response.msg;
  });
  getList();
  getDeptTree();
});
</script>

<style scoped lang="scss"></style>
